import router from '@/router'
import store from '@/store'

router.beforeEach(async(to, from, next) => {
  const url = to.path
  const token = store.state.user.token
  const whiteList = ['/login', '/404']

  // 1. 有登陆+去登录页 = 首页
  if (token && url === '/login') {
    next('/')
  }
  // 2. 有登陆+不去登录页 = 放行
  if (token && url !== '/login') {
    if (!store.getters.name) {
      const res = await store.dispatch('user/getUserInfo')
      const routers = await store.dispatch('permission/addRouter', res)
      console.log(routers)
      router.addRoutes(
        [...routers, {
          path: '*',
          redirect: '/404',
          hidden: true
        }]
      )
      next(to.path)
      return
    }
    next()
  }
  // 3. 没登录+在白名单 = 放行
  if (!token && whiteList.indexOf(url) > -1) {
    next()
  }
  // 4. 没登录+不在白名单 = 登录页
  if (!token && whiteList.indexOf(url) === -1) {
    next('/login')
  }
})
